#include "watermarklistener.h"
#include "watermarkwindow.h"

#include <QDebug>
#include <QApplication>
#include <QWindow>
#include <QScreen>
#include <QDesktopWidget>

#ifdef Q_OS_WIN32
    #include <windows.h>
#endif

WatermarkListener::WatermarkListener(QObject *parent)
    : QObject(parent)
{

}

WatermarkListener::~WatermarkListener()
{
    disconnect(QApplication::desktop(), &QDesktopWidget::screenCountChanged, this, &WatermarkListener::slotScreenCountChanged);
    stop();
}

void WatermarkListener::start()
{
    // 监听显示器数量改变
    QDesktopWidget *desktop = QApplication::desktop();
    if (desktop)
    {
        connect(desktop, &QDesktopWidget::screenCountChanged, this, &WatermarkListener::slotScreenCountChanged);
        slotScreenCountChanged(desktop->screenCount());
    }
}

void WatermarkListener::stop()
{
    for (int i = 0; i < m_watermarkWindows.count(); i++)
    {
        delete m_watermarkWindows[i];
        m_watermarkWindows[i] = nullptr;
    }
    m_watermarkWindows.clear();
}

void WatermarkListener::slotScreenCountChanged(int count)
{
    qDebug() << "current desktop screen count:" << count;
    QList<WatermarkWindow *> watermarkWindows;
    QList<QScreen *> screens = QGuiApplication::screens();
    for (QScreen *screen : screens)
    {
        WatermarkWindow *watermarkWindow = new WatermarkWindow();
        watermarkWindow->setScreen(screen);
#ifdef Q_OS_WIN32
        watermarkWindow->setGeometry(screen->geometry());
        QWindow *window = watermarkWindow->windowHandle();
        window->setScreen(screen);
#endif
#ifdef Q_OS_LINUX
        watermarkWindow->move(screen->geometry().center());
        watermarkWindow->setGeometry(screen->geometry());
#endif
        watermarkWindow->showFullScreen();
        // 监听显示器分辨率改变
        QObject::connect(screen, &QScreen::geometryChanged, watermarkWindow, [ = ](const QRect & rect)
        {
            qDebug() << "screen geometry changed:" << rect;
#ifdef Q_OS_LINUX
            watermarkWindow->move(rect.center());
            watermarkWindow->setGeometry(rect);
#endif
            watermarkWindow->showNormal();
            watermarkWindow->showFullScreen();
        });
        watermarkWindows.append(watermarkWindow);
    }

    stop();
    m_watermarkWindows = watermarkWindows;
}

void WatermarkListener::slotUpdateWatermarkWindow()
{
    for (int i = 0; i < m_watermarkWindows.count(); i++)
    {
        m_watermarkWindows[i]->update();
    }
}
